package com.zut.edu;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.zut.edu.bean.Event;
import com.zut.edu.bean.Page;
import com.zut.edu.bean.User;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.nfc.ReadTextActivity;
import com.zut.edu.nfc.ShowTextActivity;
import com.zut.edu.utils.CameraUtils;
import com.zut.edu.utils.StringUtils;
import com.zut.edu.widget.RotateTextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class PersonVerifyActivity extends AppCompatActivity {

    private int currPage = 1;
    private int pageNum = 1;
    private static final int Load = 0;
    private static final int Refresh = 1;
    private static final int LoadMore = 2;
    final int REQUEST_CODE=1;
    private Adapter mAdapter;
    @BindView(R.id.personverify_pull_layout)
    QMUIPullLayout mPullLayout;
    @BindView(R.id.personverify_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.personverify_topbar)
    QMUITopBarLayout personverifytopbar;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personverify);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);
        initTopBar();
        initData();
    }
    private void initTopBar() {
        personverifytopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        personverifytopbar.setTitle("人员审核");

    }
    private void initData(){

        mPullLayout.setActionListener(new QMUIPullLayout.ActionListener() {
            @Override
            public void onActionTriggered(@NonNull final QMUIPullLayout.PullAction pullAction) {
                mPullLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                            onRefreshData();
                        } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                            if(currPage<=pageNum)onLoadMore();
                            else{
                                Toast.makeText(PersonVerifyActivity.this,"已无更多数据",Toast.LENGTH_SHORT).show();
//                                final QMUITipDialog tipDialog = new QMUITipDialog.Builder(PersonVerifyActivity.this)
//                                        .setTipWord("已无更多数据")
//                                        .create();
//                                tipDialog.show();
//
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        try {
//                                            Thread.sleep( 1000);  //线程休眠10秒执行
//                                            tipDialog.dismiss();
//                                        } catch (InterruptedException e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                }).start();


                            }
                        }
                        mPullLayout.finishActionRun(pullAction);
                    }
                }, 1000);
            }
        });

      //  swipeAction.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });

        mAdapter = new Adapter();
        mRecyclerView.setAdapter(mAdapter);
        onDataLoaded(StringUtils.getLocalitem(this,"company","companyId"),"1",Load);
    }

    private void onDataLoaded(String companyId, String pageNo, final int action) {
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(2);
        params.put("companyId",companyId);
        params.put("pageNo",pageNo);
        okhttpHelper.get(StringUtils.BASE_URL+"/user/query", params, new BaseCallback<Page<User>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<User> userPage, int code) throws IOException {
                Log.e("onSuccess", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
                //        Collections.shuffle(eventPage.list);
                switch (action){
                    case Load:
                        pageNum = userPage.pageNum;
                        mAdapter.setData(userPage.list);
                        break;
                    case Refresh:
                        mAdapter.prepend(userPage.list);
                        break;
                    case LoadMore:
                        mAdapter.append(userPage.list);
                        break;
            }


            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }

    private void onRefreshData() {
        onDataLoaded(StringUtils.getLocalitem(this,"company","companyId"),"1",Refresh);
        mRecyclerView.scrollToPosition(0);
    }

    private void onLoadMore() {
        currPage = ++currPage;
        onDataLoaded(StringUtils.getLocalitem(this,"company","companyId"),String.valueOf(currPage),LoadMore);

    }

    class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private List<User> mData = new ArrayList<>();

        public void setData(@Nullable List<User> list) {
            mData.clear();
            if(list != null){
                mData.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void prepend(@NonNull List<User> items){
            mData.clear();
            mData.addAll(0, items);
            notifyDataSetChanged();
        }

        public void append(@NonNull List<User> items){
            mData.addAll(items);
            notifyDataSetChanged();
        }
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.personverify_list_item, parent, false);
            final RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view) {
                @Override
                public String toString() {
                    return super.toString();
                }
            };
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User user = mData.get(viewHolder.getAdapterPosition());
                    String data = JSONObject.toJSONString(user);
                    Intent intent = new Intent(PersonVerifyActivity.this, PersonVerifyDetailsActivity.class);
                    intent.putExtra("data",data);
                    startActivityForResult(intent,REQUEST_CODE);
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            TextView textView1 = holder.itemView.findViewById(R.id.text1);
            TextView textView2 = holder.itemView.findViewById(R.id.personverify_uid);
            TextView textView3 = holder.itemView.findViewById(R.id.personverify_identity);
            RotateTextView rotateTextView = holder.itemView.findViewById(R.id.personverify_rotate);
            QMUILinearLayout qmuiLinearLayout1 = holder.itemView.findViewById(R.id.personverify_uid_layout);
            QMUILinearLayout qmuiLinearLayout2 = holder.itemView.findViewById(R.id.personverify_identity_layout);
            final QMUIRadiusImageView imageView = holder.itemView.findViewById(R.id.list_img);

            textView1.setText(mData.get(position).userName);
            textView2.setText( "UID："+mData.get(position).userId);
            textView3.setText(StringUtils.statusJudge("userIdentity",mData.get(position).userIdentity));
            rotateTextView.setText(StringUtils.statusJudge("userStatus",mData.get(position).userStatus));
            setQMUILayout(qmuiLinearLayout1,R.color.qmui_config_color_blue);
            ColorStateList colorStateList = getResources().getColorStateList(StringUtils.colorJudge("userStatus",mData.get(position).userStatus));
            rotateTextView.setBackgroundTintList(colorStateList);

            setQMUILayout(qmuiLinearLayout2,StringUtils.colorJudge("userIdentity",mData.get(position).userIdentity));

            CameraUtils.initRadiusImageView(imageView,R.mipmap.user_head);
            StringUtils.photoURL(PersonVerifyActivity.this,mData.get(position).userPhoto,imageView);


        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }
    private void setQMUILayout(QMUILinearLayout layout,int id){
        layout.setBackgroundColor(getResources().getColor(id));
        layout.setBorderWidth(5);
        layout.setRadius(50);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode==RESULT_OK)onRefreshData();
        super.onActivityResult(requestCode, resultCode, data);
    }
}
